<?php
namespace backend\controller;
use backend\controller\BackendBaseController;
use backend\model\admin_access;
use backend\model\admin_role;
use jimu\Request;

class AdminaccessController extends BackendBaseController
{
    public function __construct()
    {
        parent::__construct();
    }
    //操作规则列表
    public function indexAction()
    {
        if($_SESSION['admin']['role_id'] != admin_role::ROLE_ID_SUPERADMIN){
            return '没有权限';
        }
        $access_model = new admin_access();
        $access_list = $access_model->getTreeData(0,0,true);

        $ret = [];
        foreach($access_list AS &$v){
            $ret[$v['id']] = [
                'id'=>$v['id'],
                'pId'=>$v['parent_id'],
                'name'=>$v['data'],
                'level'=>$v['level'],
                'open'=>$v['parent_id'] ==0 ? true :false,
            ];
        }
        $ret = array_values($ret);

        $this->assign('page_title','操作列表');
        $this->assign('access_list',json_encode($ret));
        $this->display('index');

    }
    //添加操作规则
    public function addAction()
    {
        $adminAccessModel = new admin_access();
        if(is_post()){
            try{
                $params = Request::post();

                $adminAccessModel->add($params);
                ajaxReturn(['code'=>1,'msg'=>'success']);
            }catch(\Exception $e){
                ajaxReturn(['code'=>$e->getCode(),'msg'=>$e->getMessage()]);
            }
        }

        $this->assign('parent_id',$adminAccessModel->getTreeData(0));
        $this->display('add');
    }

    public function delAction()
    {
        $adminAccessModel = new admin_access();
        if(is_post()){
            try{
                $params = Request::post();
                $id = $params['id'];
                $adminAccessModel->del($id);
                ajaxReturn(['code'=>1,'msg'=>'success']);
            }catch(\Exception $e){
                ajaxReturn(['code'=>$e->getCode(),'msg'=>$e->getMessage()]);
            }
        }
    }

    public function editAction()
    {
        $adminAccessModel = new admin_access();
        if(is_post()){
            try{
                $params = Request::post();
                $adminAccessModel->edit($params);
                ajaxReturn(['code'=>1,'msg'=>'success']);
            }catch(\Exception $e){
                ajaxReturn(['code'=>$e->getCode(),'msg'=>$e->getMessage()]);
            }
        }

        $_params = Request::get();
        $item = $adminAccessModel->findOne($_params['id']);

        $this->assign($item);
        $this->assign('parent_id',$adminAccessModel->getTreeData(0,$item['parent_id'],false));
        $this->display('edit');
    }
}